Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Compose custom types containing mutually exclusive keys, using this generic Typescript helper type.
The tiny npm package ts-xor
introduces the new mapped type XOR
that helps you compose your own custom TypeScript types containing mutually exclusive keys for zero runtime overhead.
ts-xor
implements the well-known exclusive or (a.k.a. XOR) logical operator from boolean algebra:
A | B | XOR | union operator (| ) | ts-xor |
---|---|---|---|---|
0 | 0 | 0 | 0 ✅ | 0 ✅ |
0 | 1 | 1 | 1 ✅ | 1 ✅ |
1 | 0 | 1 | 1 ✅ | 1 ✅ |
1 | 1 | 0 | 1 ❌ | 0 ✅ |
|
) enough?Typescript's union operator allows combining two object types A
and B
, into a superset type C which can contain all the keys of both A
and B
.
But sometimes the requirements dictate that we combine two types with mutually exclusive keys.
For example: assume two objects with with keys A.a
and B.b
. Given type C = A | B
then we want to impose the restriction that we can set either C.a
or C.b
but never both AND always at least one of the two!
Typescript does not have this feature built-in.
If we use the union operator
type A_OR_B = A | B
then the derived type is shown in VS Code like so:
Whereas if we use XOR
:
type A_XOR_B = XOR<A, B>
then the derived type is shown quite differently in VS Code:
Notice in the example above, that when using XOR
, each union branch of the resulting type contains all keys of one source type plus all keys of the other. At the same time, in each variant, those keys of the other type are defined as optional while additionally they are also typed as undefined.
This trick will not only forbid having keys of both source types defined at the same time (since the type of each key is explicitly undefined
), but also allow us to not need to define all keys all of the time since each set of keys is optional on each variant.
Fun fact: The actual TypeScript code for
XOR
is generated programmatically using the TypeScript Compiler API. 🦾
In your typescript powered, npm project, run:
npm install -D ts-xor
import type { XOR } from 'ts-xor'
interface A { a: string }
interface B { b: string }
let test: XOR<A, B>
test = { a: '' } // OK
test = { b: '' } // OK
test = { a: '', b: '' } // error
test = {} // error
If you want to create a type as the product of the logical XOR operation between multiple types (more than two and even up to 200), then just pass them as additional comma-separated generic params.
let test: XOR<A, B, C, D, E, F>
ts-xor
can easily handle up to 200 generic params. 💯
Using XOR
we can type a function that returns either the data requested from an API or a response object like so:
type FetchResult<P extends object> = XOR<
{ data: P },
{ error: FetchError<P> },
>
Now TypeScript has all the necessary information to infer if the FetchResult
contains a data
or error
key at compile time which results in very clean, yet strictly typed, handling code.
Let's assume that we have the following spec for a weather forecast API's response:
id
and station
membersrain
or a member snow
, but never both at the same time.1h
or a member 3h
with a number value, but never both keys at the same time.type ForecastAccuracy = XOR<{ '1h': number }, { '3h': number }>
interface WeatherForecastBase {
id: number
station: string
}
interface WeatherForecastWithRain extends WeatherForecastBase {
rain: ForecastAccuracy
}
interface WeatherForecastWithSnow extends WeatherForecastBase {
snow: ForecastAccuracy
}
type WeatherForecast = XOR<WeatherForecastWithRain, WeatherForecastWithSnow>
const test: WeatherForecast = {
id: 1,
station: 'Acropolis',
// rain: { '1h': 1 }, // OK
// rain: { '2h': 1 }, // error
// rain: { '3h': 1 }, // OK
// rain: {}, // error
// rain: { '1h': 1 , '3h': 3 }, // error
// lel: { '3h': 1 }, // error
// rain: { '3h': 1, lel: 1 }, // error
// snow: { '3h': 1 }, // OK
// error when BOTH `rain` AND `snow` keys are defined at the same time
}
The library ts-xor
is fully covered with smoke, acceptance and mutation tests against the typescript compiler itself. The tests can be found inside the test
folder.
To run all tests locally, execute the following command inside your git-cloned ts-xor
folder:
npm run test
This library is published on NPM.
Distributed under the MIT license. See LICENSE.md
for more information.
This project's commits comply with the Conventional Commits guidelines.
git checkout -b feat/foobar
)git commit -am 'feat(foobar): add support for foobar tricks'
)git push origin feat/fooBar
)FAQs
Compose custom types containing mutually exclusive keys, using this generic Typescript helper type.
The npm package ts-xor receives a total of 60,764 weekly downloads. As such, ts-xor popularity was classified as popular.
We found that ts-xor demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.